package java.util.stream;

import java.sql.*;

/**
 * 使用JDBC连接数据库
 *
 * @author fangjiaxiaobai@gmail.com[公众号：方家小白]
 * @date 2020-06-02 14:57
 * @since 1.0.0
 */
public class JDBCDemo {
    public static void main(String[] args) {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {

            // 1.加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            String url = "jdbc:mysql://10.127.138.75:3306/test01_jdbc";
            String username = "root";
            String password = "123456";
            /// 获取连接
            connection = DriverManager.getConnection(url, username, password);
            String sql = "show tables";
            // 创建 Statement
            preparedStatement = connection.prepareStatement(sql);
            // 执行结果，获取resultSet
            resultSet = preparedStatement.executeQuery();
            // 处理结果
            while (resultSet.next()) {
                System.out.println(resultSet.getString(1));
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            if(null!=resultSet) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(null!=preparedStatement) {
                try {
                    preparedStatement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(null!=connection) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
